<?php

namespace app\kaoqin\api;

use app\common\logic\Department;
use app\common\logic\FullRecord;
use app\common\logic\OldRecord;
use app\common\logic\User;

class Record extends Common
{
    /**
     * 原始记录首页
     * @return array|string
     * @author wb <pithyone@vip.qq.com>
     */
    public function index()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');
        $uid = getUid();

        $days = get_7days();

        if (!isset($req['t']) || empty($req['t']))
            $today = date('Y-m-d', time());
        else
            $today = date('Y-m-d', strtotime($req['t']));

        if (strtotime($today) > strtotime(date('Y-m-d', time())))
            return $this->error('时间参数错误,不能大于当前日期');

        $ret = [];
        foreach ($days as $k => $day) {
            $ret['records'][$k]['time'] = $day;
            if ($day == $today) {

                if (empty($day)) $time = time();
                else $time = strtotime($day);

                $time_start = strtotime(date('Y-m-d 00:00:00', $time));
                $time_end = strtotime(date('Y-m-d 23:59:59', $time));

                $kq_hide_userid = c('kq_hide_userid');
                if (!is_array($kq_hide_userid)) $kq_hide_userid = [$kq_hide_userid];

                $where = ['unix_time' => ['between', [$time_start, $time_end]], 'userId' => ['not in', $kq_hide_userid]];

                $kq_show_all_userid = c('kq_show_all_userid');
                if (!is_array($kq_show_all_userid)) $kq_show_all_userid = [$kq_show_all_userid];

                if (!in_array($uid, $kq_show_all_userid)) {
                    $local_user = User::get(['userid' => $uid]);
                    $dept_pid = Department::getPidById($local_user['department']);
                    $child_id = Department::getChildIds($dept_pid);

                    $where['depart_id'] = ['in', $child_id];
                }

                $records = FullRecord::getRecordByTime($where);
                $ret['records'][$k]['record'] = $this->recordDataFormat($records);
            } else $ret['records'][$k]['record'] = array();
        }

        return $this->success($ret);
    }

    public function lists()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');
        $time = date('Y-m-d');

        if (isset($req['t']) && !empty($req['t']))
            $time = date('Y-m-d', strtotime($req['t']));

        //返回当天打卡记录
        $list = FullRecord::where(['DATE(FROM_UNIXTIME(unix_time))' => $time])
            ->field("userId id,name,dept,unix_time time,unix_time")->distinct(true)->order('unix_time')->select();

        $temp = [];
        foreach ($list as $k => $v) {
            $temp[$v['id']][] = $v;
            $count = count($temp[$v['id']]);

            if ($count % 2 == 0) {
                $list[$k]['status'] = 'leave';
                $list[$k]['time_diff'] = time_diff2hour($v['unix_time'] - $list[$count / 2 + 1]['unix_time']);
            } else {
                $list[$k]['status'] = 'come';
                $list[$k]['time_diff'] = 0;
            }
        }

        usort($list, function ($a, $b) {
            return $b['unix_time'] - $a['unix_time'];
        });

        $ret = [];
        if ($time == date('Y-m-d')) {
            $time = '今天';
        } else {
            $time = date('m-d', strtotime($time)) . ' ' . get_week($time);
        }

        $ret['time'] = $time;
        $ret['list'] = $list;

        $days = [];
        $week_array = ["日", "一", "二", "三", "四", "五", "六"];

        for ($i = 6; $i >= 0; $i--) {
            $d = '-' . $i . ' day';
            $desc = date('Y年m月d日', strtotime($d));
            $simple = date('Ymd', strtotime($d));
            $day = date('d', strtotime($d));
            $week = $week_array[date("w", strtotime($d))];

            if ($simple == date('Ymd')) {
                $status = '';
            } else {
                $time_diff = [strtotime(date('Y-m-d 00:00:00', strtotime($d))), strtotime(date('Y-m-d 23:59:59', strtotime($d)))];
                $count = OldRecord::where(['userId' => getUid(), 'time' => ['between', $time_diff]])->count();
                $status = empty($count) ? '' : ($count % 2 == 0 ? 'ok' : 'error');
            }

            $days[] = ['desc' => $desc, 'simple' => $simple, 'day' => $day, 'week' => $week, 'status' => $status];
        }

        $ret['days'] = $days;

        return $this->success($ret);

    }

    /**
     * 返回格式化后的打卡记录(增加状态字段)
     * @param $records
     * @return array
     * @author wb <pithyone@vip.qq.com>
     */
    private function recordDataFormat($records)
    {
        $ret = array();
        $size = count($records);

        for ($i = $size - 1; $i >= 0; $i--) {
            $record = $records[$i];
            $count = $this->getCountInArray($ret, 'userId', $record['userId']);
            $mod = $count + 1;

            $ret[$i] = $record;
            if ($mod % 2 == 0) {
                $ret[$i]['status'] = 'leave';
                $ret[$i]['status_desc'] = '签退';
            } else {
                $ret[$i]['status'] = 'come';
                $ret[$i]['status_desc'] = '签到';
            }
        }
        ksort($ret);

        return $ret;
    }

    /**
     * 返回二维数组中查找字段的数量
     * @param $data
     * @param $key
     * @param $search
     * @return int
     * @author wb <pithyone@vip.qq.com>
     */
    private function getCountInArray($data, $key, $search)
    {
        $count = 0;
        foreach ($data as $k => $v) {
            if ($v[$key] == $search) $count++;
        }
        return $count;
    }

}